package com.hd.persistence.dao;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Query;

import com.hd.common.DataPage;
import com.hd.common.HibernateEntityDao;
import com.hd.persistence.model.PurchaseRecord;

public class PurchaseRecordDao extends HibernateEntityDao<PurchaseRecord> {

	public DataPage<PurchaseRecord> pageQueryPurchaseRecords(int pageNo, int pageSize) {
		String hql = new String("from PurchaseRecord ");
		return pagedQuery(hql, pageNo, pageSize);
	}
	
	public void savePurchaseRecord(PurchaseRecord purchaseRecord) {
		getHibernateTemplate().saveOrUpdate(purchaseRecord);
		getHibernateTemplate().flush();
	}
	
	@SuppressWarnings("unchecked")
	public PurchaseRecord findPurchaseRecordBy(String machineNo){
		String hql = new String("from PurchaseRecord where machineNo =?");
		
		List<PurchaseRecord> purchaseRecords= getHibernateTemplate().find(hql, machineNo);
		
		if(purchaseRecords.size() > 0){
			return purchaseRecords.get(0);
		}else{
			return null;
		}
	}
	
	@SuppressWarnings("unchecked")
	public DataPage<PurchaseRecord> pageQueryPurchaseRecords(Long customerId, Date contractStartDate, Date contractEndDate, String machineModel, int pageNo, int pageSize) {
		StringBuilder hql = new StringBuilder("from PurchaseRecord pr left join fetch pr.customer left join fetch pr.machineInfo where (1=1) ");
		List<Object> objs = new ArrayList<Object>();
		if ( customerId != null ) {
			hql.append("and pr.customer.id=? ");
			objs.add(customerId);
		}
		if ( contractStartDate != null ) {
			hql.append("and pr.contractStartDate=? ");
			objs.add(contractStartDate);
		}
		if ( contractEndDate != null ) {
			hql.append("and pr.contractEndDate=? ");
			objs.add(contractEndDate);
		}
		if ( StringUtils.isNotBlank(machineModel) ) {
			hql.append("and pr.machineModel=? ");
			objs.add(machineModel);
		}
		
		// Count查询
		String countQueryString = " select count(*) " + hql.toString().replaceAll("fetch", "");
		List countlist = getHibernateTemplate().find(countQueryString, objs.toArray());
		int totalCount = ((Long) countlist.get(0) ).intValue();

		if (totalCount < 1)
			return new DataPage<PurchaseRecord>();
		// 实际查询返回分页对象
		int startIndex = DataPage.getStartOfPage(pageNo, pageSize);
		String queryStr = "select pr " + hql.toString() + " order by createTimestamp desc ";
		Query query = createQuery(queryStr, objs.toArray());
		List<PurchaseRecord> list = query.setFirstResult(startIndex).setMaxResults(pageSize).list();

		return new DataPage<PurchaseRecord>(startIndex, totalCount, pageSize, list);
	}
}
